package com.malex.mxtracker.util;

import com.malex.mxtracker.bean.Currency;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.List;

/**
 * @author Manusovich Alexander
 */
public class NBRBXMLParser extends DefaultHandler {
    private List<Currency> list;
    private String value;

    public NBRBXMLParser(final List<Currency> list) {
        list.clear();
        this.list = list;
    }

    @Override
    public void startElement(final String uri,
                             final String localName,
                             final String qName,
                             final Attributes attributes) throws SAXException {
        if ("Currency".equals(qName)) {
            list.add(new Currency());
        }
    }

    @Override
    public void characters(final char[] ch,
                           final int start,
                           final int length) throws SAXException {
        value = new String(ch, start, length);
    }

    @Override
    public void endElement(final String uri,
                           final String localName,
                           final String qName) throws SAXException {
        Currency currency;
        if (list.size() > 0) {
            currency = list.get(list.size() - 1);
        } else {
            return;
        }
        if ("CharCode".equals(qName)) {
            currency.setCharCode(value);
        }
        if ("Name".equals(qName)) {
            currency.setName(value);
        }
        if ("Rate".equals(qName)) {
            currency.setRate(Double.valueOf(value));
        }
    }
}
